package com.cy.store.controller;

import com.cy.store.controller.ex.*;
import com.cy.store.service.ex.*;
import com.cy.store.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

public class BaseController {
    public static final int Ok=200;

    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e){
        JsonResult<Void> jsonResult = new JsonResult<>();
        if (e instanceof UsernameDuplicatedException){
            jsonResult.setState(4000);
            jsonResult.setMessage("用户名已被注册异常");
        }else if (e instanceof AddressCountLimitException){
            jsonResult.setState(4001);
            jsonResult.setMessage("收货地址已达上限");
        }else if (e instanceof AddressNotFoundException){
            jsonResult.setState(4002);
            jsonResult.setMessage("收货地址信息不存在");
        }else if (e instanceof AccessDeniedException){
            jsonResult.setState(4003);
            jsonResult.setMessage("非法访问");
        }else if (e instanceof DeleteException){
            jsonResult.setState(4004);
            jsonResult.setMessage("删除时产生未知异常");
        }else if (e instanceof ProductNotFoundException){
            jsonResult.setState(4005);
            jsonResult.setMessage("商品信息不存在异常");
        }else if (e instanceof CartNotFoundException){
            jsonResult.setState(4006);
            jsonResult.setMessage("购物车数据不存在异常");
        }else if (e instanceof UserNotFoundException){
            jsonResult.setState(5001);
            jsonResult.setMessage("用户数据不存在异常");
        }else if (e instanceof PasswordNotMatchException){
            jsonResult.setState(5002);
            jsonResult.setMessage("用户密码不匹配异常");
        }else if (e instanceof InsertException){
            jsonResult.setState(5000);
            jsonResult.setMessage("注册过程发生未知异常");
        }else if (e instanceof UpdateException){
            jsonResult.setState(5003);
            jsonResult.setMessage("更新数据时产生未知异常");
        }else if (e instanceof FileEmptyException) {
            jsonResult.setState(6000);
        } else if (e instanceof FileSizeException) {
            jsonResult.setState(6001);
        } else if (e instanceof FileTypeException) {
            jsonResult.setState(6002);
        } else if (e instanceof FileStateException) {
            jsonResult.setState(6003);
        } else if (e instanceof FileUploadIOException) {
            jsonResult.setState(6004);
        }
        return jsonResult;
    }

    /**
     * 从session获取Uid
     * @param session
     * @return
     */
    protected final Integer getUidFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("uid").toString());
    }

    /**
     * 从session获取username
     * @param session
     * @return
     */
    protected final String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }
}
